package com.pricl.frame.common.web.rest;

import java.util.List;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springside.modules.mapper.JsonMapper;
import org.springside.modules.web.MediaTypes;

/**
 * <ol>
 * <li>构建响应的对象工具</li>
 * <ol>
 * 
 * @author jackzhong
 * @since 2014年10月24日下午11:49:33
 */
public final class RestResponseBuilder {

	private RestResponse restResponse;
	private JsonMapper jsonMapper = null;

	public RestResponseBuilder() {
		this(RestResponseCode.getSuccessResponseCode(), "");
	}

	public RestResponseBuilder(String responseMsg) {
		this(RestResponseCode.getSuccessResponseCode(), responseMsg);
	}

	public RestResponseBuilder setFailureResCode() {
		this.restResponse.setResponseCode(RestResponseCode.getFailureResponseCode());
		return this;
	}

	public RestResponseBuilder(String responseCode, String responseMsg) {
		restResponse = new RestResponse(responseCode, responseMsg);
		jsonMapper = JsonMapper.nonEmptyMapper();
	}

	/**
	 * 设置结果集
	 * 
	 * @param dataList
	 */
	public <T> RestResponseBuilder setResultData(Object data) {
		restResponse.setResponseData(data);
		return this;
	}

	public RestResponse builder() {
		return restResponse;
	}

	public String builderToJsonString() {
		return jsonMapper.toJson(restResponse);
	}

	private HttpHeaders getHeaders() {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType(MediaTypes.JSON_UTF_8));
		return headers;
	}

	public <T> ResponseEntity<RestResponse> builderResponseEntity() {
		return builderResponseEntity(null);
	}

	public <T> ResponseEntity<RestResponse> builderResponseEntity(List<T> dataList) {
		if (dataList != null) {
			restResponse.setResponseData(dataList);
		}
		return new ResponseEntity<RestResponse>(restResponse, getHeaders(), HttpStatus.OK);
	}
}
